package com.guomei.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AesUtils {
    // 密钥和偏移量（需与前端完全一致）
    private static final String KEY = "1234567890abcdef"; // 16位
    private static final String IV = "abcdef1234567890";  // 16位
    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";

    /**
     * AES加密（CBC模式）
     * @param plaintext 明文
     * @return 加密后的Base64字符串
     */
    public static String encrypt(String plaintext) {
        try {
            // 密钥和偏移量处理
            SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes("UTF-8"), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes("UTF-8"));

            // 加密模式初始化
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);

            // 加密并Base64编码
            byte[] encryptedData = cipher.doFinal(plaintext.getBytes("UTF-8"));
            return Base64.getEncoder().encodeToString(encryptedData);
        } catch (Exception e) {
            throw new RuntimeException("加密失败", e);
        }
    }

    /**
     * AES解密（CBC模式）
     * @param ciphertext 加密后的Base64字符串
     * @return 解密后的明文
     */
    public static String decrypt(String ciphertext) {
        try {
            // 密钥和偏移量处理
            SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes("UTF-8"), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes("UTF-8"));

            // 解密模式初始化
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

            // Base64解码后解密
            byte[] encryptedData = Base64.getDecoder().decode(ciphertext);
            byte[] decryptedData = cipher.doFinal(encryptedData);

            return new String(decryptedData, "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException("解密失败", e);
        }
}

    public static void main(String[] args) {
        String encrypt = encrypt("123456");
        System.out.println(encrypt);
    }
}
